package com.pay.ioopos.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.pay.ioopos.KeyInfo;
import com.pay.ioopos.KeyInfoListener;
import com.pay.ioopos.PwdCheckerDefault;
import com.pay.ioopos.PwdChecker;
import com.pay.ioopos.R;
import com.pay.ioopos.fragment.PwdInputFragment.OnPwdListener;


public class PwdCheckerFragment extends Fragment implements OnPwdListener, KeyInfoListener {
    private final Handler handler = new Handler();
    private PwdInputFragment pwdInput = new PwdInputFragment();
    private PwdChecker pwdChecker;
    private OnPwdValidateListener listener;
    public PwdCheckerFragment() {
        setPwdChecker(new PwdCheckerDefault());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_password, container, false);

        pwdInput.setOnPwdListener(this);

        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.password_main_container, pwdInput);
        fragmentTransaction.commit();

        return view;
    }

    public void setPwdChecker(PwdChecker pwdChecker) {
        this.pwdChecker = pwdChecker;
    }

    public void setOnPwdValidateListener(OnPwdValidateListener listener) {
        this.listener = listener;
    }

    @Override
    public boolean onKeyDown(KeyInfo keyInfo) {
        return pwdInput.onKeyDown(keyInfo);
    }

    @Override
    public void finish(String pwd) {
        boolean isValid = pwdChecker.isValid(pwd);
        if (!isValid) {
            handler.post(() -> Toast.makeText(pwdInput.getContext(), pwdInput.getContext().getString(R.string.pwd_invalid), Toast.LENGTH_SHORT).show());
            handler.postDelayed(() -> pwdInput.clear(), 300);
            if (null != listener) {
                listener.onInvalid(pwd);
            }

        } else {
            if (null != listener) {
                listener.onValid(pwd);
            }
        }
    }

    public interface OnPwdValidateListener {
        void onValid(String pwd);
        void onInvalid(String pwd);
    }
}
